package com.sunwayworld.basemodule.samplemanage.samplecodegenerate.validators;

import com.sunwayworld.basemodule.samplemanage.samplecodegenerate.bean.LimsSamplecodeGenerateBean;
import com.sunwayworld.basemodule.samplemanage.samplecodegenerate.bean.LimsSamplecodeGenerateRecordBean;
import com.sunwayworld.basemodule.samplemanage.samplecodegenerate.service.LimsSamplecodeGenerateService;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.CollectionUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.framework.validator.data.DataValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
@GikamBean
/*
* 样本编码生成删除，校验生成记录是否全部未使用，存在使用的则无法删除
* */
public class LimsGenerateDeleteValidator implements DataValidator {

    @Autowired
    private LimsSamplecodeGenerateService generateService;

    @Override
    public boolean doValid(Object... args) {
        RestJsonWrapperBean wrapper = (RestJsonWrapperBean) args[0];
        boolean result = true;
        List<LimsSamplecodeGenerateBean> generates = wrapper.parse(LimsSamplecodeGenerateBean.class);
        if (CollectionUtils.isEmpty(generates)) {
            return result;
        }
        // 获取生成数据ID
        List<Long> generateIds = generates.stream().map(LimsSamplecodeGenerateBean::getId).collect(Collectors.toList());
        // 重查原始数据
        List<LimsSamplecodeGenerateBean> nowGenerates = generateService.selectListByFilter(SearchFilter.instance()
            .match("ID", generateIds).filter(MatchPattern.OR));
        if (CollectionUtils.isEmpty(nowGenerates)) {
            return result;
        }
        for ( LimsSamplecodeGenerateBean generateBean : nowGenerates) {
            if (!StringUtils.equals(String.valueOf(generateBean.getBarcodeNum())
                ,String.valueOf(generateBean.getExt$Item("CNT_NOTINUSE")))) {
                // 未使用条码数和生成条码数不一致，则存在已经使用的条码
                this.addConstraintViolation("存在已使用的样本编码，无法删除！");
                result = false;
                return result;
            }
        }
        return result;
    }
}
